#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2024-07-09 12:58:18
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   日志中间件
'''
import time

from starlette.middleware.base import BaseHTTPMiddleware, DispatchFunction
from starlette.types import ASGIApp
from fastapi import Request, Response

from ..jwt.is_pass import isPass

class LogMiddleware(BaseHTTPMiddleware):
    """日志中间件"""
    def __init__(self, app:ASGIApp, header_namespace:str):
        super().__init__(app)
        self.header_namespace = header_namespace

    async def dispatch(self, # type: ignore
                       request: Request, 
                       call_next: DispatchFunction) -> Response:
        response: Response = await call_next(request) # type: ignore
        username = ""
        if isPass(request.url.path):
            return response # type: ignore
        else:
            username = request.state.data.get("username")
        request_tiem = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        from_host = request.headers.get("host")
        action = request.url.path
        result_message = "成功"
        if response.status_code != 200: # type: ignore
            result_message = "失败"
        print(f"{request_tiem} {username}，从{from_host}来，做了{action}，结果{result_message}")
        return response # type: ignore
